<?php

namespace app\shop\controller;

// 框架基础控制类
use think\Controller;
use think\Request;

class Order extends Controller
{
    //构造函数
    public function __construct()
    {
        //手动把父类的方法获取过来
        parent::__construct();

        // check_cors_request();

        // 全局用户模型
        $this->BusinessModel = model('Business.Business');
        $this->RecordModel = model('Business.Record');
        $this->ProductModel = model('Product.Product');
        $this->CartModel = model('Product.Cart');
    }

    // 下单
    public function add()
    {
        $busid = $this->request->param('busid', 0, 'trim');
        $proid = $this->request->param('proid', '', 'trim');
        $amount = $this->request->param('amount', 0, 'trim');
        $remark = $this->request->param('remark', '', 'trim');

        $userinfo = $this->BusinessModel->find($busid);

        if (!$userinfo) {
            $this->error('当前用户不存在');
        }

        $productlist = $this->CartModel->with('product')->where('cart.id', 'in', $proid)->select();

        if (!$productlist) {
            $this->error('当前购物车产品不存在');
        }

        // 订单产品表
        $orderproductdata = [];
        // 产品表
        $productdata = [];

        foreach ($productlist as $item) {
            if (!$item['product']) {
                $this->error('当前下单商品不存在');
                break;
            }

            $productinfo = $this->ProductModel->find($item['product']['id']);

            $updatestock = bcsub($productinfo['stock'], $item['nums']);

            if ($updatestock < 0) {
                $this->error($productinfo['name'] . "商品库存不足");
                break;
            }

            $productdata[] = [
                'id' => $productinfo['id'],
                'stock' => $updatestock
            ];

            $items = [
                'orderid' => $this->OrderModel->id,
                'proid' => $productinfo['id'],
                'pronum' => $item['nums'],
                'price' => $item['price'],
                'total' => $item['total']
            ];

            $orderproductdata[] = $items;

            // 验证器不能校验二维数组
            $orderproductsvalidate = $this->validate($items, 'common/Order/OrderProduct');
            if (true !== $orderproductsvalidate) {
                // 验证失败 输出错误信息
                $this->error($orderproductsvalidate);
            }
        }

        echo '---';
        exit;
    }
}
